import React, { useState, useEffect } from 'react';
import { Form, Button, Divider, Input, Select, TreeSelect, DatePicker } from 'antd';
import defaultSetting from '../../../../../../config/defaultSettings';
import { connect } from 'umi';
import styles from './index.less';
import E from 'wangeditor';
import {
  addCommodity,
  queryStoreList,
  UploadCommodity,
  uploadCommodityStep,
  queryCategory,
} from '../../service';
import { handleData, transTitle } from '@/utils/utils';
const { Option } = Select;
let editor = null;
const Step1 = (props) => {
  const { defaultVal, data, dataSoure, handleCurrent, handleId, CommodityId, reviseState } = props;
  const [content, setContent] = useState('');
  const [guarantee, setGuarantee] = useState(false);
  const [form] = Form.useForm();
  const [treeValue, handleTreeValue] = useState();
  const [expireTime, handleExpireTime] = useState();
  // const [menuValues, setMenuValues] = useState([]);
  const [category, setCategory] = useState([]);
  const [categoryName, handleCategoryName] = useState();
  const TreeOnChange = (value, label, extra) => {
    handleTreeValue(label.id);
  };
  // const getStore = () => {
  //   queryStoreList().then((res) => {
  //     if (res.code === 0) {
  //       const { data } = res;
  //       transTitle(data);
  //       setMenuValues(data);
  //     }
  //   });
  // };
  const getCategory = () => {
    queryCategory().then((res) => {
      if (res.code === 0) {
        const { data } = res;
        transTitle(data);
        setCategory(data);
      }
    });
  };
  useEffect(() => {
    // getStore();
    getCategory();
    editor = new E('#div1');
    editor.config.onchange = (newHtml) => {
      setContent(newHtml);
    };
    editor.config.uploadFileName = 'file';
    editor.config.uploadImgServer = `${defaultSetting.baseUrl}/common/upload?module=edit`;
    editor.config.uploadImgMaxSize = 2 * 1024 * 1024;
    editor.config.uploadImgAccept = [];
    editor.config.uploadImgShowBase64 = true;
    editor.config.uploadImgHeaders = {
      token: sessionStorage.getItem('token'),
      type: 'ADMIN',
    };

    editor.config.uploadImgHooks = {
      // 上传图片之前

      // 图片上传并返回了结果，图片插入已成功
      success: function (xhr) {},
      // 图片上传并返回了结果，但图片插入时出错了
      fail: function (xhr, editor, resData) {},
      // 上传图片出错，一般为 http 请求的错误
      error: function (xhr, editor, resData) {
        return {
          prevent: true,
          msg: '上传错误',
        };
      },
      // 上传图片超时
      timeout: function (xhr) {},
      // 图片上传并返回了结果，想要自己把图片插入到编辑器中
      // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
      customInsert: function (insertImgFn, result) {
        // result 即服务端返回的接口

        // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
        insertImgFn(result.data.url);
      },
    };
    /**一定要创建 */
    editor.create();
    defaultVal ? editor.txt.html(defaultVal.description) : null;
    return () => {
      editor.destroy();
    };
  }, []);
  const { validateFields } = form;
  const onValidateForm = async () => {
    const editHtml = editor.txt.html();
    const values = await validateFields();
    values.description = editHtml;
    values.categoryName = categoryName;
    values.generatedDate = new Date(values.generatedDate).getTime();
    if (guarantee) {
      values.expireDate = values.generatedDate + expireTime * 86400000;
    } else {
      values.expireDate = new Date(expireTime).getTime();
    }
    dataSoure.map((item) => {
      return item.id === values.brandId ? (values.brandName = item.name) : null;
    });
    // menuValues.map((item_) => {
    //   return item_.id === values.storeId ? (values.storeName = item_.name) : null;
    // });
    reviseState ? (values.id = CommodityId) : null;
    return reviseState
      ? UploadCommodity(values).then((res) => {
          if (res.code === 0) {
            handleCurrent(1);
          }
        })
      : addCommodity(values).then((res) => {
          if (res.code === 0) {
            const { data } = res;
            handleId(data);
            uploadCommodityStep(data, 1);
            handleCurrent(1);
          }
        });
  };
  const lableStyle = {
    labelCol: { span: 4 },
    wrapperCol: { span: 24 },
  };
  return (
    <>
      <Form
        form={form}
        layout="horizontal"
        labelAlign="right"
        className={styles.stepForm}
        hideRequiredMark
        {...lableStyle}
        initialValues={defaultVal ? defaultVal : ''}
      >
        <Form.Item
          label="商品名称"
          name="name"
          rules={[
            {
              required: true,
              message: '请填写商品名称',
            },
          ]}
        >
          <Input placeholder="请输入商品名称" />
        </Form.Item>
        <Form.Item label="品牌" name="brandId">
          <Select placeholder="请选择品牌">
            {dataSoure.map((item, index) => {
              return (
                <Option value={item.id} key={index}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>
        <Form.Item
          label="商品分类"
          name="categoryId"
          rules={[
            {
              required: true,
              message: '请选择商品分类',
            },
          ]}
        >
          <TreeSelect
            showSearch
            dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
            placeholder="请选择分类"
            allowClear
            key="key"
            treeDataSimpleMode
            treeData={category}
            treeNodeFilterProp="title"
            treeNodeLabelProp="title"
            onSelect={(e, val) => {
              return handleCategoryName(val.name);
            }}
          />
          {/* <Select
            placeholder="请选择分类"
            onChange={(e, val) => {
              console.log(e, val);
              handleCategoryName(val.children);
            }}
          >
            {category.map((item, index) => {
              return (
                <Option value={item.id} key={index}>
                  {item.name}
                </Option>
              );
            })}
          </Select> */}
        </Form.Item>
        <Form.Item label="生产日期" name="generatedDate">
          <DatePicker format="YYYY-MM-DD" />
        </Form.Item>
        <Form.Item
          label="保质期"
          name="expireDate"
          style={{ display: 'flex', justifyContent: 'flex-start', alignItems: 'center' }}
        >
          {guarantee ? (
            <Input
              type="number"
              style={{ maxWidth: 380 }}
              onChange={(e) => {
                handleExpireTime(e.target.value);
              }}
            />
          ) : (
            <DatePicker
              format="YYYY-MM-DD"
              onChange={(e) => {
                handleExpireTime(e);
              }}
            />
          )}
          <Button
            type="link"
            onClick={() => {
              setGuarantee(!guarantee);
            }}
          >
            {guarantee ? '切换日期' : '切换天数'}
          </Button>
        </Form.Item>
        <Form.Item label="批次号" name="batchNo">
          <Input placeholder="请输入批次号" />
        </Form.Item>
        <Form.Item
          label="条码号"
          name="barCode"
          rules={[
            {
              required: true,
              message: '条码号必填',
            },
          ]}
        >
          <Input placeholder="请输入条码号" />
        </Form.Item>
        <Form.Item
          label="是否赠送积分"
          name="isIntegral"
          rules={[
            {
              required: true,
              message: '是否赠送积分必选',
            },
          ]}
        >
          <Select placeholder="请选择是否赠送积分">
            <Option value={true} key={1}>
              是
            </Option>
            <Option value={false} key={0}>
              否
            </Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="标价"
          name="price"
          rules={[
            {
              required: true,
              message: '请填写标价',
            },
          ]}
        >
          <Input placeholder="请输入标价" />
        </Form.Item>
        <Form.Item
          label="是否称重"
          name="weigh"
          rules={[
            {
              required: true,
              message: '是否称重必选',
            },
          ]}
        >
          <Select placeholder="请选择是否称重">
            <Option value={true} key={1}>
              是
            </Option>
            <Option value={false} key={0}>
              否
            </Option>
          </Select>
        </Form.Item>
        <Form.Item
          label="是否自有产品"
          name="self"
          rules={[
            {
              required: true,
              message: '是否自有产品必选',
            },
          ]}
        >
          <Select placeholder="请选择是否自有产品">
            <Option value={true} key={1}>
              是
            </Option>
            <Option value={false} key={0}>
              否
            </Option>
          </Select>
        </Form.Item>
      </Form>
      <Form.Item label="商品描述" name="description" style={{ zIndex: 0 }}>
        <div id="div1" style={{ maxWidth: 1020, marginLeft: 10 }}></div>
      </Form.Item>
      <div className={styles.bottomBtn}>
        <Button type="primary" onClick={onValidateForm}>
          下一步
        </Button>
      </div>
    </>
  );
};

export default connect(({ commodityManagementAndCommodityCreatingSteps }) => ({
  data: commodityManagementAndCommodityCreatingSteps.step,
}))(Step1);
